package com.mailbox.mailbox.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mailbox.mailbox.domain.Message;
import com.mailbox.mailbox.domain.Page;
import com.mailbox.mailbox.domain.Reply;
import com.mailbox.mailbox.domain.responsePojo.ReturnReply;
import com.mailbox.mailbox.mapper.MessageMapper;
import com.mailbox.mailbox.mapper.ReplyMapper;
import com.mailbox.mailbox.service.MessageService;
import com.mailbox.mailbox.util.ResponseResult;
import lombok.NonNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Administrator
 * @description 针对表【message】的数据库操作Service实现
 * @createDate 2022-05-15 08:45:05
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Resource
    ReplyMapper replyMapper;
    @Resource
    MessageMapper messageMapper;
    @Override
    public ResponseResult findAllMessages(@NonNull Integer page, @NonNull Integer size) {
        Integer counts = this.baseMapper.findCounts();
        Page sort = sort(page, size,counts);
        if (sort==null){
            return ResponseResult.error("没有数据");
        }
        List<Message> list = this.baseMapper.findAllMessages(sort.getPageNo(), sort.getPageSize());
        if (list!=null){
            sort.setPageNo(sort.getPageNo()+1);
            return ResponseResult.success(list,sort);
        }else {
            return ResponseResult.error("没有数据");
        }
    }

    @Override
    public ResponseResult findSuchMessages(@NonNull Integer page,@NonNull Integer size, String messageType, String startTime,String endTime) {
        List<Message> list;
        Page sort;
        if (messageType!=null){
            if (startTime!=null && endTime!=null){
                Integer w = this.baseMapper.selectBySuchCounts(messageType, startTime, endTime);
                sort = sort(page, size,w);
                if (sort.getPageNo()==null){
                    return ResponseResult.error("没有数据");
                }
                list = this.baseMapper.findSuchMessage(startTime, endTime, messageType, sort.getPageNo(), sort.getPageSize());
            }else {
                Integer w = this.baseMapper.selectByTypeCounts(messageType);
                System.out.println(w);
                sort = sort(page, size,w);
                if (sort.getPageNo()==null){
                    return ResponseResult.error("没有数据");
                }
                list = this.baseMapper.findSuchMessageType(messageType, sort.getPageNo(), sort.getPageSize());
            }
        }else {
            if (startTime!=null && endTime!=null){
                Integer w = this.baseMapper.selectByTimeCounts(startTime, endTime);
                sort = sort(page, size,w);
                if (sort.getPageNo()==null){
                    return ResponseResult.error("没有数据");
                }
                list = this.baseMapper.findSuchMessageTime(startTime, endTime, sort.getPageNo(), sort.getPageSize());
                System.out.println(list);
            }else {
                Integer counts = this.baseMapper.findCounts();
                sort = sort(page, size,counts);
                if (sort.getPageNo()==null){
                    return ResponseResult.error("没有数据");
                }
                list = this.baseMapper.findAllMessages(sort.getPageNo(), sort.getPageSize());
            }
        }
        if (list!=null){
            sort.setPageNo(sort.getPageNo()+1);
            return ResponseResult.success(list,sort);
        }else {
            return ResponseResult.error("没有数据");
        }
    }

    @Override
    public ResponseResult selectByPhone(@NonNull Integer page,@NonNull Integer size,@NonNull String phone) {
        String temp="[^(0-9)]";
        Matcher matcher= Pattern.compile(temp).matcher(phone);
        if (matcher.find() || phone.length()>11){
            return ResponseResult.error("电话格式错误");
        }
        Page page1=new Page();
        page = page - 1;
        Integer i=0;
        int maxCount=0;
        if (size > 0 && page >= 0) {
            i = this.baseMapper.selectByPhoneCounts(phone);
            if (i == 0) {
                return ResponseResult.error("没有数据");
            }
            maxCount = i % size == 0 ? i / size : i / size + 1;
            if (page >= maxCount) {
                page = (maxCount - 1) * size;
            } else {
                page = page * size;
            }
        }
        page1.setPageNo(page);
        page1.setPageSize(size);
        page1.setPageNoTotal(maxCount);
        page1.setPageSizeTotal(i);
        List<Message> list=this.baseMapper.selectByPhone(phone,page1.getPageNo(),page1.getPageSize());
        if (list!=null){
            page1.setPageNo(page1.getPageNo()+1);
            return ResponseResult.success(list,page1);
        }else {
            return ResponseResult.error("没有留言");
        }
    }

    @Override
    public ResponseResult selectByName(@NonNull Integer page, @NonNull Integer size, @NonNull String name) {
        String regex1 ="[\\u4e00-\\u9fa5]+";
        boolean matches = name.matches(regex1);
        if (!matches || name.length()>20){
            return ResponseResult.error("姓名格式错误");
        }
        Page page1=new Page();
        page = page - 1;
        Integer i=0;
        int maxCount=0;
        if (size > 0 && page >= 0) {
            i = this.baseMapper.selectByNameCounts(name);
            if (i == 0) {
                return ResponseResult.error("没有数据");
            }
            maxCount = i % size == 0 ? i / size : i / size + 1;
            if (page >= maxCount) {
                page = (maxCount - 1) * size;
            } else {
                page = page * size;
            }
        }
        page1.setPageNo(page);
        page1.setPageSize(size);
        page1.setPageNoTotal(maxCount);
        page1.setPageSizeTotal(i);
        List<Message> list=this.baseMapper.selectByName(name,page1.getPageNo(),page1.getPageSize());
        if (list!=null){
            page1.setPageNo(page1.getPageNo()+1);
            return ResponseResult.success(list,page1);
        }else {
            return ResponseResult.error("没有留言");
        }
    }

    @Override
    public ResponseResult selectByEmail(@NonNull Integer page, @NonNull Integer size,@NonNull String email) {
        Page page1=new Page();
        page = page - 1;
        Integer i=0;
        int maxCount=0;
        if (size > 0 && page >= 0) {
            i= this.baseMapper.selectByEmailCounts(email);
            if (i == 0) {
                return ResponseResult.error("没有数据");
            }
            maxCount = i % size == 0 ? i / size : i / size + 1;
            if (page >= maxCount) {
                page = (maxCount - 1) * size;
            } else {
                page = page * size;
            }
        }
        page1.setPageNo(page);
        page1.setPageSize(size);
        page1.setPageNoTotal(maxCount);
        page1.setPageSizeTotal(i);
        List<Message> list=this.baseMapper.selectByEmail(email,page1.getPageNo(),page1.getPageSize());
        if (list!=null){
            page1.setPageNo(page1.getPageNo()+1);
            return ResponseResult.success(list,page1);
        }else {
            return ResponseResult.error("没有留言");
        }
    }

    @Override
    public ResponseResult selectByContent(@NonNull Integer page, @NonNull Integer size, @NonNull String content) {
        Page page1=new Page();
        page = page - 1;
        Integer i=0;
        int maxCount=0;
        if (size > 0 && page >= 0) {
            i= this.baseMapper.selectByContentCounts(content);
            if (i == 0) {
                return ResponseResult.error("没有数据");
            }
            maxCount = i % size == 0 ? i / size : i / size + 1;
            if (page >= maxCount) {
                page = (maxCount - 1) * size;
            } else {
                page = page * size;
            }
        }
        page1.setPageNo(page);
        page1.setPageSize(size);
        page1.setPageNoTotal(maxCount);
        page1.setPageSizeTotal(i);
        List<Message> list=this.baseMapper.selectByContent(content,page1.getPageNo(),page1.getPageSize());
        if (list!=null){
            page1.setPageNo(page1.getPageNo()+1);
            return ResponseResult.success(list,page1);
        }else {
            return ResponseResult.error("没有留言");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteMessages(@NonNull String ids) {
        StringBuffer temp = new StringBuffer();
        if (ids == null) {
            return ResponseResult.error("未传入值");
        }
        temp.append("(");
        String[] strArray = ids.split(",");
        if (strArray != null && strArray.length > 0) {
            for (int i = 0; i < strArray.length; i++) {
                temp.append("'");
                temp.append(strArray[i]);
                temp.append("'");
                if (i != (strArray.length - 1)) {
                    temp.append(",");
                }
            }
        }
        temp.append(")");
        boolean b = this.baseMapper.deleteMessages(temp.toString());
        boolean c=replyMapper.deleteReply(temp.toString());
        if (b) {
            return ResponseResult.success("删除成功");
        }
        return ResponseResult.error("删除失败");
    }

    @Override
    public ResponseResult findUnSee(@NonNull Integer page,@NonNull Integer size,@NonNull Integer status) {
        PageHelper.startPage(page,size);
        //未查看
        if(status==0){
            List<Message>list=this.list(new QueryWrapper<Message>().eq("is_reply",0));
            PageInfo<Message> pageInfo=new PageInfo<>(list);
            return ResponseResult.success("查询成功",pageInfo);
        }else if(status==1){
            //已回复
            List<Message>list=messageMapper.findReplyMsg();
            PageInfo<Message> pageInfo=new PageInfo<>(list);
            return ResponseResult.success("查询成功",pageInfo);
        }else if(status==2){
            //未回复
            List<Message>list=messageMapper.findNotReplyMsg();
            PageInfo<Message> pageInfo=new PageInfo<>(list);
            return ResponseResult.success("查询成功",pageInfo);
        }else if(status==3){
            //已公开
            List<Message>list=messageMapper.findOpen();
            PageInfo<Message> pageInfo=new PageInfo<>(list);
            return ResponseResult.success("查询成功",pageInfo);
        }else if(status==4){
            //未公开
            List<Message>list=messageMapper.findNotOpen();
            PageInfo<Message> pageInfo=new PageInfo<>(list);
            return ResponseResult.success("查询成功",pageInfo);
        }
        return ResponseResult.error("系统繁忙");


    }

    @Override
    public ResponseResult findUnSeeCounts(@NonNull Integer status) {
        if(status==0){
            long count=this.count(new QueryWrapper<Message>().eq("is_reply",0));
            return ResponseResult.success(count);
        }else if(status==1){
            //已回复
            Long count=messageMapper.countReplyMsg();
            return ResponseResult.success(count);
        }else if(status==2){
            //未回复
            Long count=messageMapper.countNotReplyMsg();
            return ResponseResult.success(count);
        }else if(status==3){
            //已公开
            Long count=messageMapper.countOpen();
            return ResponseResult.success(count);
        }else if(status==4){
            //未公开
            Long count=messageMapper.countNotOpen();
            return ResponseResult.success(count);
        }
        return ResponseResult.error("系统繁忙");

    }

    @Override
    public ResponseResult findOpenMessage(Integer pageNow,Integer pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        QueryWrapper<Message>queryWrapper=new QueryWrapper<>();
        List<Message>list=this.list(queryWrapper.eq("is_reply",3));
        PageInfo<Message> pageInfo=new PageInfo<>(list);
        return ResponseResult.success("查询成功",pageInfo);
    }

    @Override
    public ResponseResult findNotOpenMessage(Integer pageNow,Integer pageSize) {
        PageHelper.startPage(pageNow,pageSize);
        List<Message>list=messageMapper.findNotOpen();
        PageInfo<Message> pageInfo=new PageInfo<>(list);
        return ResponseResult.success("查询成功",pageInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult openMessage(Integer messageId) {
        QueryWrapper<Reply> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("message_id",messageId);
        Reply reply=replyMapper.selectOne(queryWrapper);
        if(reply==null){
            return ResponseResult.error("该信件未回复,不能公开");
        }
        boolean b=this.update().setSql("is_open=1")
                .eq("message_id",messageId).update();
        if(!b){
            return ResponseResult.error("系统繁忙,请稍后再试");
        }
        return ResponseResult.success("公开成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult closeMessage(Integer messageId) {
        boolean b=this.update().setSql("is_open=0")
                .eq("message_id",messageId).update();
        if(!b){
            return ResponseResult.error("系统繁忙,请稍后再试");
        }

        return ResponseResult.success("关闭公开成功");
    }


    public Page sort(Integer page, Integer size,Integer w){
        Page page1=new Page();
        page = page - 1;
        Integer i=0;
        int maxCount=0;
        if (size > 0 && page >= 0) {
            i = w;
            if (i == 0) {
                return page1;
            }
            maxCount = i % size == 0 ? i / size : i / size + 1;
            if (page >= maxCount) {
                page = (maxCount - 1) * size;
            } else {
                page = page * size;
            }
        }
        page1.setPageNo(page);
        page1.setPageSize(size);
        page1.setPageNoTotal(maxCount);
        page1.setPageSizeTotal(i);
        return page1;
    }

}



